package io.lvdaxian.mybatis09.executor;

import io.lvdaxian.mybatis09.executor.statement.StatementHandler;
import io.lvdaxian.mybatis09.mapping.BoundSql;
import io.lvdaxian.mybatis09.mapping.MappedStatement;
import io.lvdaxian.mybatis09.session.Configuration;
import io.lvdaxian.mybatis09.session.ResultHandler;
import io.lvdaxian.mybatis09.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * 这里实现了 基础的执行器
 *
 * @author lihh
 */
public class SimpleExecutor extends BaseExecutor {
  
  public SimpleExecutor(Configuration configuration, Transaction transaction) {
    super(configuration, transaction);
  }
  
  @Override
  protected <E> List<E> doQuery(MappedStatement ms, Object parameter, ResultHandler resultHandler, BoundSql boundSql) {
    Configuration configuration = ms.getConfiguration();
    
    // 接口 StatementHandler 中封装了整个请求的过程
    StatementHandler statementHandler = configuration.newStatementHandler(this, ms, parameter, resultHandler, boundSql);
    try {
      // 通过事务拿到连接
      Connection connection = transaction.getConnection();
      // 准备阶段 拿到 statement
      Statement statement = statementHandler.prepare(connection);
      // 参数设置的阶段
      statementHandler.parameterize(statement);
      
      return statementHandler.query(statement, resultHandler);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
}
